// Copyright 2020 Apulis Technology Inc. All rights reserved.

package controller

import (
	"apedge/dto"
	"apedge/pkg/common"
	"apedge/pkg/loggers"
	"apedge/pkg/protocol"
	"apedge/pkg/validators"
	"reflect"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

var logger = loggers.LogInstance()

var validWorker = validators.ValidatorInstance()

// pre handler is used to handle the common logic of each comming request
func PreHandler(c *gin.Context, reqContent interface{}) (*protocol.UserInfoAAA, *dto.APIErrorResp) {
	var err error

	// check reqContent type
	contentType := reflect.TypeOf(reqContent)
	switch contentType.Kind() {
	case reflect.Ptr:
		break
	default:
		logger.Errorf("PreHandler: reqContent is not a pointer")
		return nil, dto.ServerError(c)
	}

	// validate request content
	err = validWorker.Struct(reqContent)
	if err != nil {
		errs, _ := err.(validator.ValidationErrors)
		for _, validationError := range errs {
			if validationError.Tag() == "name-checker" {
				return nil, dto.AppError(c, common.NAME_CHECK_ERROR_CODE, err.Error())
			}
		}
		return nil, dto.ParameterError(c, err.Error())
	}

	userInfo := protocol.UserInfoAAA{}

	c.ShouldBindHeader(&userInfo)
	if err != nil {
		return nil, dto.ParameterError(c, err.Error())
	}
	logger.Infof("-----------------  %+v", userInfo)
	return &userInfo, nil
}
